package cn.itcast.hotel;

import cn.itcast.hotel.pojo.HotelDoc;
import com.alibaba.fastjson.JSON;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpHost;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.*;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.Aggregation;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.aggregations.metrics.Stats;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.util.CollectionUtils;

import javax.naming.directory.SearchResult;
import java.io.IOException;
import java.util.List;
import java.util.Map;

@SpringBootTest
public class EsSearchDemo {

    @Test
    public void aggregations2() throws IOException {

        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.size(0);
        //设置聚合参数
        source.aggregation(AggregationBuilders.stats("statsAgg")//自定义聚合名称
                .field("price"));//对价格今昔计算

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 获取总和的聚合结果
        Aggregations aggregations = response.getAggregations();
        // 根据自定义的聚合名称  获取指定的聚合结果
        Stats statsResult = aggregations.get("statsAgg");
        System.out.println("平均价格:"+statsResult.getAvg());
        System.out.println("最大价格:"+statsResult.getMax());
        System.out.println("最小价格:"+statsResult.getMin());
        System.out.println("求和价格:"+statsResult.getSumAsString());
        System.out.println("总数量:"+statsResult.getCount());
    }
        @Test
    public void aggregations1() throws IOException {
            // 按照品牌进行分组   打印每个分组名称   和  分组内酒店文档的数量
            SearchRequest request = new SearchRequest("hotel");
            SearchSourceBuilder source = request.source();
            source.size(0);
            //设置聚合参数
            source.aggregation(AggregationBuilders.terms("brandAgg")//自定义聚合名称
                    .field("brand")//按照品牌分组
                    .size(20));//显示分组的数量
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 获取总和的聚合结果
            Aggregations aggregations = response.getAggregations();
            // 根据自定义的聚合名称  获取指定的聚合结果
            Terms terms = aggregations.get("brandAgg");
            //获取结果中的 buckets 分组信息
            List<? extends Terms.Bucket> buckets = terms.getBuckets();
            //遍历分组   打印每个分组的 key和 文档数量
            for (Terms.Bucket bucket : buckets) {
                System.out.println("======================");
                System.out.println("当前分组key值:" + bucket.getKeyAsString());
                System.out.println("当前分组文档数量:" + bucket.getDocCountError());
                System.out.println("======================");
            }

        }




    @Test
    public void highlight() throws IOException {
        //创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.query(QueryBuilders.matchQuery("all", "外滩如家"));
        //高亮条件设置
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("name");//那个字段高亮
        highlightBuilder.preTags("<span>");//前置标签
        highlightBuilder.postTags("<span>");//后置标签
        highlightBuilder.requireFieldMatch(false);//不做所搜字段检查
        source.highlighter(highlightBuilder);


        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }

    @Test
    public void sortAndPage() throws IOException {
        //第几页
        int page = 1;
        //每页显示多少条
        int size = 3;

        //创建请求
        SearchRequest request = new SearchRequest("hotrl");
        SearchSourceBuilder source = request.source();
        // 拍照评价   降序排序
        source.sort("score", SortOrder.DESC);
        //如果评分一致    按照价格升序排序
        source.sort("price", SortOrder.ASC);
        //设置分页参数
        source.from((page - 1) * size);
        source.size(size);

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }


    /**
     * 查询名称中包含：  上海外滩   match ：name  上海外滩
     * 价格： range  500-1000
     * 排除品牌
     *
     * @throws IOException
     */
    @Test
    public void bool() throws IOException {
        //创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        // 创建布尔条件
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        //使用布尔条件对象,组合其他基础条件
        MatchQueryBuilder matchQueryBuilder = QueryBuilders.matchQuery("name", "上海外滩");
        boolQuery.must(matchQueryBuilder);
        RangeQueryBuilder priceBuilder = QueryBuilders.rangeQuery("price").gte(500).lt(1000);
        boolQuery.filter(priceBuilder);

        TermQueryBuilder termQueryBuilder = QueryBuilders.termQuery("brand", "万怡");
        boolQuery.mustNot(termQueryBuilder);
        //设置布尔条件
        source.query(boolQuery);
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);

    }

    @Test
    public void range() throws IOException {
        //创建请求
        SearchRequest request = new SearchRequest("hotrl");
        SearchSourceBuilder source = request.source();
        source.query(QueryBuilders.rangeQuery("proce").gte(1000).lt(1500));

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);

    }

    /**
     * 查询   品牌  希尔顿
     */
    @Test
    public void term() throws IOException {
        //创建请求
        SearchRequest request = new SearchRequest("hotrl");
        SearchSourceBuilder source = request.source();
        source.query(QueryBuilders.termQuery("brand", "希尔顿"));

        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);

    }


    /**
     * 查询全部
     */
    @Test
    public void matchAll() throws IOException {
        //创建请求
        SearchRequest request = new SearchRequest("hotrl");
        SearchSourceBuilder source = request.source();
        //构建条件
        source.query(QueryBuilders.matchAllQuery());
        // 执行请求
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        // 解析结果
        printResult(response);

    }

    private void printResult(SearchResponse response) {
        //解析结果
        SearchHits hits = response.getHits();
        System.out.println("查询到的文档数量:" + hits.getTotalHits().value);
        for (SearchHit hit : hits) {
            String hotelJson = hit.getSourceAsString();
            //现在得到的文档内容  并没有高亮处理的结果
            HotelDoc hotelDoc = JSON.parseObject(hotelJson, HotelDoc.class);
            //单独获取高亮处理结果
            Map<String, HighlightField> highlightFields = hit.getHighlightFields();
            if (!CollectionUtils.isEmpty(highlightFields)) {
                //关于文档name 字段的高亮处理结果
                HighlightField highlightField = highlightFields.get("name");
                //将高亮片段拼接成完整的字符串
                String join = StringUtils.join(highlightField.getFragments());
                //用高亮处理结果  替换之前的name字段内容
                hotelDoc.setName(join);
                System.out.println(hotelDoc);
            }
        }


    }

    /**
     * 分词查询   macth  name:外滩如家
     */
    @Test
    public void match() throws IOException {
        //创建请求
        SearchRequest request = new SearchRequest("hotel");
        SearchSourceBuilder source = request.source();
        source.query(QueryBuilders.matchQuery("name", "外滩如家"));
        SearchResponse response = client.search(request, RequestOptions.DEFAULT);
        printResult(response);
    }


    @BeforeEach
    public void init() {
        //1. 准备号客户端对象
        client = new RestHighLevelClient
                (RestClient.builder(HttpHost.create("http://192.168.200.130:9200")));

    }

    RestHighLevelClient client;

    @AfterEach
    public void close() {
        try {
            client.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
